package com.biubiux2.codec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author Lijinbao
 * @since 8/5/2022 6:43 PM
 */
@Deprecated
public class ByteBufToString extends MessageToMessageCodec<ByteBuf, String> {

    private static final class ByteBufToStringHolder {
        static final ByteBufToString byteBufToString = new ByteBufToString();
    }

    public static ByteBufToString getInstance() {
        return ByteBufToStringHolder.byteBufToString;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, String msg, List<Object> out) throws Exception {
        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
        buffer.readBytes(msg.getBytes(StandardCharsets.UTF_8));
        out.add(buffer);
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
        int len = msg.readableBytes();
        byte[] bytes = new byte[len];
        String s = new String(bytes, StandardCharsets.UTF_8);
        out.add(s);
    }
}
